package com.realtyManage.springboot.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.realtyManage.springboot.Config.WxProgramPayConfig;
import com.realtyManage.springboot.Dao.DictionariesZeroRepository;
import com.realtyManage.springboot.Model.Do.*;
import com.realtyManage.springboot.Model.Vo.*;
import com.realtyManage.springboot.Service.*;
import com.realtyManage.springboot.Service.impl.DictionariesServiceImpl;
import com.realtyManage.springboot.Service.impl.HouseFansServiceImpl;
import com.realtyManage.springboot.Service.impl.UserTaskServiceImpl;
import com.realtyManage.springboot.Utils.*;
import com.realtyManage.springboot.Word.WordUtils;
import com.realtyManage.springboot.wxpay.PayUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.tomcat.util.http.fileupload.util.LimitedInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * IndexController
 *
 * @Author 杭州素色网络科技有限公司
 * @Date 2019/7/22
 * 首页控制器
 **/

@Controller
@RequestMapping("/")
public class IndexController {
    @Autowired
    private IPanicBuyService pbService;

    @Autowired
    private IIndexService indexService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IBannerService bannerService;

    @Autowired
    private IAnnouncementService announcementService;

    @Autowired
    private IIndexHotHouseService indexHotHouseService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IHouseDetailService houseDetailService;

    @Autowired
    private ISpecialOfferHouseService specialOfferHouseService;

    @Autowired
    private ICodeService codeService;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private ICityCodeService cc;

    @Autowired
    private  ICustomerRegistrationService customerRegistrationService;

    @Autowired
    private DictionariesService dictionariesService;

    @Autowired
    private IHouseFansService houseFansService;

    @Autowired
    private DictionariesServiceImpl dictionariesServiceImp;

    @Autowired
    private HouseFansServiceImpl houseFansServiceImp;

    @Autowired
    private UserTaskServiceImpl userTaskService;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    protected BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private IActiveService activeService;

    @Autowired
    private DictionariesZeroRepository dictionariesZeroRepository;

    @ResponseBody
    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public HashMap<String,List> index(@RequestParam String areaId, HttpServletRequest request, HttpServletResponse response){
        HashMap<String,List> map = new HashMap<String,List>();
        List<Banner> banner = bannerService.getIndexBanner(1,areaId);

        map.put("banner",banner);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/houseDetail",method = RequestMethod.GET)
    public HouseDetail houseDetail(@RequestParam Integer hid){
        HouseDetail s = indexService.getHouseDetail(hid);
        return indexService.getHouseDetail(hid);
    }

    @ResponseBody
    @RequestMapping(value = "/houseDetail/{hid}",method = RequestMethod.GET)
    public String houseDetail1(@PathVariable Integer hid) {
        return JSON.toJSONString(indexService.getHouseDetail(hid));
    }

    @ResponseBody
    @RequestMapping(value = "/banner",method = RequestMethod.GET)
    public String banner(@RequestParam(value="area",required=false)String area,HttpServletRequest request) {
        return JSON.toJSONString(bannerService.getIndexBanner(1,area));
    }

    @ResponseBody
    @RequestMapping(value = "/announcement",method = RequestMethod.GET)
    public String announcement(HttpServletRequest request) {
        if(request.getSession().getAttribute("level")==null || Integer.parseInt(request.getSession().getAttribute("level").toString())==1){
            return JSON.toJSONString(announcementService.findByStateAndType(1,1));
        }else{
            return JSON.toJSONString(announcementService.findByStateAndTypeGatherThanEqual(1,1));
        }
    }

    /**
     * 查询异地主推楼盘列表
     * @param area
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/fieldHotHouse",method = RequestMethod.GET)
    public String fieldHotHouse(@RequestParam String area,HttpServletRequest request) {
        List<HouseDetail> list = new ArrayList<>();
        long ll = 60*60*12;
        //查询异地显示到本地主推楼盘
            List<Integer> houseDetailList = indexHotHouseService.findByPeripheryLike(area);
            if (houseDetailList.size() >0){
                for (int i=0;i<houseDetailList.size();i++){
                    list.add(indexService.getHouseDetail(houseDetailList.get(i)));
                }
            }else{
                BaseEntity baseEntity = new BaseEntity();
                baseEntity.setInfoCode(-1);
                baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(-1));
                return JSON.toJSONString(baseEntity);
            }
        return JSON.toJSONString(list);

    }

    /**
     * 修改版获取主推楼盘数据
     * @param area
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/hotHouse",method = RequestMethod.GET)
    public String hotHouse(@RequestParam String area,HttpServletRequest request) {
        List<HouseDetail> list = new ArrayList<>();
        long ll = 60*60*12;
        boolean isValue = redisService.exists(area+"hotHouse");
        if (isValue){
            Object ob = redisService.get(area+"hotHouse");
            return JSON.toJSONString(ob);
        }else{
            List<IndexHotHouse> indexHotHouseList = indexHotHouseService.findByAreaLike(area);
            if(indexHotHouseList!=null && indexHotHouseList.size() > 0){
                if(!StringUtils.deleteWhitespace(indexHotHouseService.findByAreaLike(area).get(0).getHotHouse()).equals("")){
                    String ids = "";
                    for (int i =0;i< indexHotHouseList.size();i++){
                        ids += indexHotHouseList.get(i).getHotHouse()+",";
                    }
                    String[] houseIds = ids.split(",");
                    for (String hid : houseIds) {
                        list.add(indexService.getHouseDetail(Integer.parseInt(hid)));
                    }
                    redisService.remove(area+"hotHouse");
                    redisService.set(area+"hotHouse",list,ll);

                }
                return JSON.toJSONString(list);
            }else{
                BaseEntity baseEntity = new BaseEntity();
                baseEntity.setInfoCode(-105);
                baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(-105));
                return JSON.toJSONString(baseEntity);
            }
        }

    }

    /**
     * 抢购和订单信息
     * @param panicBuy
     * @param request
     * @return
     */
    @RequestMapping(value = "/savePanicBuy",method = RequestMethod.POST)
    private String saveSpecialOfferHouse(PanicBuy panicBuy, HttpServletRequest request) {
        BaseEntity entity = new BaseEntity();
        String userName = userService.findByName(panicBuy.getUid());
        Order order = new Order();
        order.setOrderId(panicBuy.getOrderId());
        order.setOrderMoney(1.0);
        order.setOrderUserId(panicBuy.getUid());
        order.setOrderDetail("带看费");
        order.setOrderTime(new Date());
        order.setUserName(userName);
        orderService.saveOrder(order);
        String houseName = houseDetailService.getName(panicBuy.getHouseId());
        int code = 0;
        if(!panicBuy.getHid().equals("")){
            panicBuy.setHouseName(houseName);
            panicBuy.setInvalidTime(new Date());
            if (pbService.save(panicBuy) != null){
                code = 1;
                //更改特价房状态 isShow 1
                SpecialOfferHouse specialOfferHouse  =  specialOfferHouseService.getIdAllOne(panicBuy.getHid());
                specialOfferHouse.setIsShow(1);
                SpecialOfferHouse count = specialOfferHouseService.updateSpecialOfferHouseType(specialOfferHouse);
            }else{
                code  = -1;
            }
        }
        entity.setInfoCode(code);
        entity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(entity);
    }

    /**
     * 特价房源管理
     * chenxinlele
     * userId 用户id
     */
    @ResponseBody
    @RequestMapping(value = "/findSpecialOfferHouseByUserId",method = RequestMethod.GET)
    private String  findSpecialOfferHouseByUserId(@RequestParam String userId,HttpServletRequest request){
        String houserId = houseDetailService.getId(userId); //获取用户管理的楼盘id
        List<SpecialOfferHouse> list = new ArrayList<SpecialOfferHouse>();
        if (!userId.equals("")){
            list = specialOfferHouseService.findSpecialOfferHouseByHouseId(houserId);
        }else {
            BaseEntity entity = new BaseEntity();
            entity.setInfoCode(-1);
            entity.setInfoText(SysExecRsUtil.getMsgFromCode(-1));
            return JSON.toJSONString(entity);
        }
        return JSON.toJSONString(list);
    }


    /**
     * 认购和打回抢购列表
     * @param specialOfferHouseId
     * @param specialOfferHouseType
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateSpecialOfferHouseType",method = RequestMethod.POST)
    private  String updateSpecialOfferHouseType(@RequestParam Integer specialOfferHouseId,@RequestParam Integer specialOfferHouseType,HttpServletRequest request){
        Integer code = 1;
        if (!specialOfferHouseType.equals("")){
            SpecialOfferHouse specialOfferHouse  =  specialOfferHouseService.getIdAll(specialOfferHouseId);
            specialOfferHouse.setIsShow(specialOfferHouseType);
            SpecialOfferHouse count = specialOfferHouseService.updateSpecialOfferHouseType(specialOfferHouse);
               if (count != null){
                   code = 1;
               }else{
                   code = -1;
               }
        }
        BaseEntity entity = new BaseEntity();
        entity.setInfoCode(code);
        entity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(entity);
    }


    @ResponseBody
    @RequestMapping(value = "/wxNotify",method = RequestMethod.GET)
    public void wxNotify(HttpServletRequest request,HttpServletResponse response) throws Exception {
        System.out.println("进入回调方法=========================================》");
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        //sb为微信返回的xml
        String notityXml = sb.toString();
        String resXml = "";
        System.out.println("接收到的报文：" + notityXml);

        Map map = PayUtil.doXMLParse(notityXml);

        String returnCode = (String) map.get("return_code");
        if ("SUCCESS".equals(returnCode)) {
            //验证签名是否正确
            Map<String, String> validParams = PayUtil.paraFilter(map);  //回调验签时需要去除sign和空值参数
            String validStr = PayUtil.createLinkString(validParams);//把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
            String sign = PayUtil.sign(validStr, WxProgramPayConfig.KEY, "utf-8").toUpperCase();//拼装生成服务器端验证的签名
            //根据微信官网的介绍，此处不仅对回调的参数进行验签，还需要对返回的金额与系统订单的金额进行比对等
            if (sign.equals(map.get("sign"))) {
                /**此处添加自己的业务逻辑代码start**/


                /**此处添加自己的业务逻辑代码end**/
                //通知微信服务器已经支付成功
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            }
        } else {
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        System.out.println(resXml);
        System.out.println("微信支付回调数据结束");


        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }

    //文章列表
    @ResponseBody
    @RequestMapping(value = "/articleList",method = RequestMethod.GET)
    public String articleList(@RequestParam(value = "type", required=false)Integer type, @RequestParam("pageNumber")Integer pageNumber,@RequestParam("pageSize")Integer pageSize,HttpServletRequest request) {
        Page<Article> a = articleService.findPagedByTypeAndState(type,1,pageNumber,pageSize);
        return JSON.toJSONString(articleService.findPagedByTypeAndStateWy(type,1,pageNumber,pageSize));
    }

    //文章详情
    @ResponseBody
    @RequestMapping(value = "/getDetail",method = RequestMethod.GET)
    public String articleDetail(HttpServletRequest request) {
        String artId = request.getParameter("artId");
        return JSON.toJSONString(articleService.getOne(Integer.valueOf(artId)));
    }

    //获取首页
    @ResponseBody
    @RequestMapping(value = "/getHomePage",method = RequestMethod.GET)
    public String getHomePage(HttpServletRequest request) {
        return JSON.toJSONString(articleService.getHomePage());
    }

    @ResponseBody
    @RequestMapping(value = "/findCode",method = RequestMethod.GET)
    private String  findCode(HttpServletRequest request){
        String sCode = null;
        List<Code> list = codeService.findCode();
        for (int i = 1;i<list.size();i++){
            CityCode c = new CityCode();
            String name = "江苏省"+list.get(0).getName1()+"市"+list.get(i).getName1();
            sCode = list.get(0).getCode2() +","+ list.get(i).getCode2();
            String eCode = list.get(i).getCode1();
            String zCode = sCode+","+eCode;
            System.out.println("name===================>"+name+"==================code=================>"+zCode);
            c.setyName(name);
            c.setCode(zCode);
            CityCode a  = cc.infoCode(c);
        }
        return JSON.toJSONString(list);
    }


    @ResponseBody
    @RequestMapping(value = "/querySalesperson",method = RequestMethod.GET)
    private String querySalesperson(HttpServletRequest request){
        List cr = customerRegistrationService.querySalesperson();
        return  JSON.toJSONString(cr);
    }

    /**
     * 查询客户来访记录
     * @param request
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping(value = "/queryCountComeSalesperson",method = RequestMethod.GET)
    private String queryCountComeSalesperson(HttpServletRequest request) throws ParseException {
        Integer num = 0;
        List<Map<String,Object>> list1 = new ArrayList<Map<String,Object>>();
        Map<String,Object> m1 = new LinkedHashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
        Map<String,String> map = new HashMap<>();
        Calendar c = Calendar.getInstance();
        String sTime = request.getParameter("sTime");
        String eTime = request.getParameter("eTime");
        String uid = request.getParameter("uid");
        Integer year = Integer.valueOf(eTime.substring(0,4));
        String m = eTime.substring(5,7);
        boolean month = m.indexOf("0" ) != -1;
        if (month){
             m = m.replace("0","");
        }
        c.set(year, Integer.valueOf(m), 0); //输入类型为int类型
        int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
        //判断时间间隔是整月查询
        if (sTime.substring(8,10).equals("01") && eTime.substring(8,10).equals(String.valueOf(dayOfMonth))){
            if (sTime.substring(0,7).equals(eTime.substring(0,7))){
                List<Object> cr = customerRegistrationService.queryCountComeSalesperson(sTime,eTime,uid);
                for (int j=0;j<cr.size();j++) {
                    Object[] objects = (Object[]) cr.get(j);
                    Integer value = customerRegistrationService.queryCountCustomNum(objects[0].toString(),uid);
                    m1.put(objects[0].toString(),value);
                }
            }else{
                List<Object> cr = customerRegistrationService.queryCountComeSalespersonMonth(sTime,eTime,uid);
                for (int j=0;j<cr.size();j++) {
                    Object[] objects = (Object[]) cr.get(j);
                    Integer value = customerRegistrationService.queryCountCustomNum(objects[0].toString(),uid);
                    m1.put(objects[0].toString(),value);
                }
            }
        }else{
            List<Object> cr = customerRegistrationService.queryCountComeSalesperson(sTime,eTime,uid);
            for (int j=0;j<cr.size();j++) {
                Object[] objects = (Object[]) cr.get(j);
                Integer value = customerRegistrationService.queryCountCustomNum(objects[0].toString(),uid);
                m1.put(objects[0].toString(),value);
            }
        }
        list1.add(m1);
        return  JSON.toJSONString(list1);
    }

    /**
     * 客户意向类型
     * @param request
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping(value = "/queryCountIntention",method = RequestMethod.GET)
    private String queryCountIntention(HttpServletRequest request) throws ParseException {
        String sTime = request.getParameter("sTime");
        String eTime = request.getParameter("eTime");
        String uid = request.getParameter("uid");
        //判断时间间隔是整月查询
        List<String> cr = customerRegistrationService.queryCountIntention(sTime,eTime,uid);
        return  JSON.toJSONString(cr);
    }

    /**
     * 面积需求
     * @param request
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping(value = "/queryCountAreaNeed",method = RequestMethod.GET)
    private String queryCountAreaNeed(HttpServletRequest request) throws ParseException {
        String sTime = request.getParameter("sTime");
        String eTime = request.getParameter("eTime");
        String uid = request.getParameter("uid");
        //判断时间间隔是整月查询
        List<String> cr = customerRegistrationService.queryCountAreaNeed(sTime,eTime,uid);
        return  JSON.toJSONString(cr);
    }

    /**
     * 我的客户列表
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryMyCustomerList",method = RequestMethod.GET)
    private String queryMyCustomerList(CustomReEntity customReEntity, HttpServletRequest request){
        Page<CustomerRegistration> cr = customerRegistrationService.queryMyCustomerList(customReEntity,userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId());
        return  JSON.toJSONString(cr);
    }

    /**
     * 我的客户列表下面汇总
     * @param customReEntity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryMyCustomerListE",method = RequestMethod.GET)
    private String queryMyCustomerListE(CustomReEntity customReEntity, HttpServletRequest request){
        List<Integer> cr = customerRegistrationService.queryMyCustomerListE(customReEntity,userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId());
        return  JSON.toJSONString(cr);
    }

    /***
     * 修改客户销售信息
     * @param customReEntity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/modifyComoCustom",method = RequestMethod.POST)
    private String modifyComoCustom(CustomReEntity customReEntity,HttpServletRequest request){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Integer code = -1;
        if (customerRegistrationService.modifyComoCustom(customReEntity) > 0){
            code = 1;
        }
        BaseEntity baseEntity =new BaseEntity();
        baseEntity.setInfoCode(code);
        baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return  JSON.toJSONString(baseEntity);
    }

    /**
     * 客户销售分析
     * @param customReEntity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryCustomerList",method = RequestMethod.GET)
    private String queryCustomerList(CustomReEntity customReEntity, HttpServletRequest request){
        List<String> cr = customerRegistrationService.queryCustomerList(customReEntity);
        return  JSON.toJSONString(cr);
    }


    /**
     * 我的销售分析
     * @param customReEntity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryPersonalCustomerList",method = RequestMethod.GET)
    private String queryPersonalCustomerList(CustomReEntity customReEntity, HttpServletRequest request){
        Integer uid = userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId();
        ArrayList<String> list = new ArrayList<>();
        if (customReEntity.getsTime() != null && customReEntity.geteTime() != null){
             list = customerRegistrationService.queryTeamRCustomerList(customReEntity.getsTime(),customReEntity.geteTime()+" 23:59:59",uid);
        }
        return JSON.toJSONString(list);
    }

    /**
     * 团队销售分析
     * @param customReEntity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryTeamCustomerList",method = RequestMethod.GET)
    private String queryTeamCustomerList(CustomReEntity customReEntity, HttpServletRequest request){
        ArrayList<String> list = new ArrayList<>();
        if (customReEntity.getsTime() != null && customReEntity.geteTime() != null){
             list = customerRegistrationService.queryTeamERCustomerList(customReEntity.getsTime(),customReEntity.geteTime()+" 23:59:59");
        }
        return JSON.toJSONString(list);
    }

    /**
     * 团队客户列表
     * @param customReEntity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/teamCustomerList",method = RequestMethod.GET)
    private String teamCustomerList(CustomReEntity customReEntity, HttpServletRequest request){
        Page<CustomerRegistration> lst = customerRegistrationService.teamCustomerList(customReEntity);
        return JSON.toJSONString(lst);
    }

    /**
     * 团队客户列表下面统计汇总
     * @param customReEntity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/teamCustomerListE",method = RequestMethod.GET)
    private String teamCustomerListE(CustomReEntity customReEntity, HttpServletRequest request){
        List<Integer> cr = customerRegistrationService.teamCustomerListE(customReEntity);
        return  JSON.toJSONString(cr);
    }


    /**
     * 我的客户销售分析
     * @param customReEntity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/querySalesAnalysisOfMyCustomers",method = RequestMethod.GET)
    private String querySalesAnalysisOfMyCustomers(CustomReEntity customReEntity, HttpServletRequest request){
        customReEntity.setReceptionId(userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId().toString());
        JSONArray lst = customerRegistrationService.querySalesAnalysisOfMyCustomers(customReEntity);
        return JSON.toJSONString(lst);
    }

    /**
     * 查询我的排名 （销售佣金统计）
     * @param customReEntity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryMyRank",method = RequestMethod.GET)
    private String queryMyRank(CustomReEntity customReEntity, HttpServletRequest request){
        JSONArray lst = customerRegistrationService.queryMyRank(customReEntity);
        return JSON.toJSONString(lst);
    }

    /**
     * 查询团队排名 （销售佣金统计）
     * @param customReEntity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryTeamRank",method = RequestMethod.GET)
    private String queryTeamRank(CustomReEntity customReEntity, HttpServletRequest request){
        JSONArray lst = customerRegistrationService.queryTeamRank(customReEntity);
        return JSON.toJSONString(lst);
    }

    /**
     * 团队客户信息
     * @param customReEntity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/querySalesAnalysisOfTeamCustomers",method = RequestMethod.GET)
    private String querySalesAnalysisOfTeamCustomers(CustomReEntity customReEntity, HttpServletRequest request){
        JSONArray lst = customerRegistrationService.querySalesAnalysisOfTeamCustomers(customReEntity);
        return JSON.toJSONString(lst);
    }


    /**
     * 我的来访数据汇总
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryComeCustomerNum",method = RequestMethod.GET)
    private String queryComeCustomerNum(HttpServletRequest request){
        List<String> cr = customerRegistrationService.queryComeCustomerNum(userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId());
        return  JSON.toJSONString(cr);
    }

    /**
     * 房源状态列表参数
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getHouseParameter")
    private String getHouseParameter(HttpServletRequest request) {
        String type = request.getParameter("type");
        List<String> houseMapParameter = houseDetailService.getHouseParameter(type);
        return JSON.toJSONString(houseMapParameter);
    }

    /**
     * 我的客户分析
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/myCustomerAnalysis",method = RequestMethod.GET)
    private String myCustomerAnalysis(HttpServletRequest request){
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
        //根据前传入得状态判断时间格式
        String type = request.getParameter("type"); //状态  0全部 1本月 2上月 3本年度
        String time = null;
        if (type.equals("1")){
            time = sd.format(new Date()); //本月
        }else if (type.equals("2")){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH) - 1);
            time = sd.format(calendar.getTime()); //上月*/
        }else if (type.equals("3")){
            Calendar calendar = Calendar.getInstance();
            time = calendar.get(Calendar.YEAR)+"";
        }else {
            time = "0"; //全部
        }
        List<String> cr = customerRegistrationService.myCustomerAnalysis(time,userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId());
        return  JSON.toJSONString(cr);
    }


    /**
     * 我的客户来访区域分析
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/myComeCustomer",method = RequestMethod.GET)
    private String myComeCustomer(HttpServletRequest request){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String type = request.getParameter("type"); //状态  0全部 1本月 2上月 3本年度
        String areaCode = request.getParameter("areaCode"); //区域编码
        String time = null;
        if (type.equals("1")){
            time = sdf.format(new Date()); //本月
        }else if (type.equals("2")){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH) - 1);
            time = sdf.format(calendar.getTime()); //上月*/
        }else if (type.equals("3")){
            Calendar calendar = Calendar.getInstance();
            time = calendar.get(Calendar.YEAR)+"";
        }
       List<String> cr = customerRegistrationService.myComeCustomer(time,areaCode,userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId());
        return  JSON.toJSONString(cr);
    }


    /**
     * 我的转化率
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/myConversionRate",method = RequestMethod.GET)
    private String myConversionRate(HttpServletRequest request){
        List lst = new ArrayList();
        String sTime = request.getParameter("sTime");
        String eTime = request.getParameter("eTime");
        List<Object> myRate = customerRegistrationService.myConversionRate(sTime,eTime,userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId());
        int yy = 0,lf =0,rc =0,cj=0,ef=0,zf = 0,yf=0,azlfs = 0; //预约数,来访数,认筹数,成交数,二访数,总访数,预约来访
        if (myRate.size() >  0){
            for (int j = 0;j < myRate.size();j ++){
                Object[] objects = (Object[]) myRate.get(j);
                yy = Integer.valueOf(objects[0].toString());
                azlfs = Integer.valueOf(objects[1].toString());
                lf = Integer.valueOf(objects[2].toString());
                rc = Integer.valueOf(objects[3].toString());
                cj = Integer.valueOf(objects[4].toString());
                ef = Integer.valueOf(objects[5].toString());
                zf = Integer.valueOf(objects[6].toString());
                yf = zf - ef;
            }
        }

        int gys = 1;
        int smaller = yy > azlfs ? azlfs : yy;
        for (int i = 1; i <= smaller; i++) {
            if (yy % i == 0 && azlfs % i == 0) {
                gys = i;
            }
        }
        int lrGys = 1;
        int lrSmaller = lf > rc ? rc : lf;
        for (int i = 1; i <= lrSmaller; i++) {
            if (lf % i == 0 && rc % i == 0) {
                lrGys = i;
            }
        }
        int rcGys = 1;
        int cjSmaller = rc > cj ? cj : rc;
        for (int i = 1; i <= cjSmaller; i++) {
            if (rc % i == 0 && cj % i == 0) {
                rcGys = i;
            }
        }
        int lGys = 1;
        int lSmaller = yf > ef ? ef : yf;
        for (int i = 1; i <= lSmaller; i++) {
            if (yf % i == 0 && ef % i == 0) {
                lGys = i;
            }
        }
        lst.add( yy / gys + ":" + azlfs / gys);
        lst.add( lf / lrGys + ":" + rc / lrGys);
        lst.add( rc / rcGys + ":" + cj / rcGys);
        lst.add( yf / lGys + ":" + ef / lGys);
        return  JSON.toJSONString(lst);
    }


    /**
     * 团队转化率分析
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/teamConversionRate",method = RequestMethod.GET)
    private String teamConversionRate(HttpServletRequest request){
        List lst = new ArrayList();
        String sTime = request.getParameter("sTime");
        String eTime = request.getParameter("eTime");
        List<Object> teamRate = customerRegistrationService.teamConversionRate(sTime,eTime);
        int ld = 0,lf =0,rc =0,cj=0,ef=0,zf = 0,yf=0,ldlfs = 0; //来电数,来访数,认筹数,成交数,二访数,总访数,来电来访数
        if (teamRate.size() >  0){
            for (int j = 0;j < teamRate.size();j ++){
                Object[] objects = (Object[]) teamRate.get(j);
                ld = Integer.valueOf(objects[0].toString());
                ldlfs = Integer.valueOf(objects[1].toString());
                lf = Integer.valueOf(objects[2].toString());
                rc = Integer.valueOf(objects[3].toString());
                cj = Integer.valueOf(objects[4].toString());
                ef = Integer.valueOf(objects[5].toString());
                zf = Integer.valueOf(objects[6].toString());
                yf = zf - ef;
            }
        }

        int gys = 1;
        int smaller = ld > ldlfs ? ldlfs : ld;
        for (int i = 1; i <= smaller; i++) {
            if (ld % i == 0 && ldlfs % i == 0) {
                gys = i;
            }
        }
        int lrGys = 1;
        int lrSmaller = lf > rc ? rc : lf;
        for (int i = 1; i <= lrSmaller; i++) {
            if (lf % i == 0 && rc % i == 0) {
                lrGys = i;
            }
        }
        int rcGys = 1;
        int cjSmaller = rc > cj ? cj : rc;
        for (int i = 1; i <= cjSmaller; i++) {
            if (rc % i == 0 && cj % i == 0) {
                rcGys = i;
            }
        }
        int lGys = 1;
        int lSmaller = yf > ef ? ef : yf;
        for (int i = 1; i <= lSmaller; i++) {
            if (yf % i == 0 && ef % i == 0) {
                lGys = i;
            }
        }
        lst.add( ld / gys + ":" + ldlfs / gys);
        lst.add( lf / lrGys + ":" + rc / lrGys);
        lst.add( rc / rcGys + ":" + cj / rcGys);
        lst.add( zf / lGys + ":" + ef / lGys);
        return  JSON.toJSONString(lst);
    }

    /**
     * 获取字典表
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getDictionaries",method = RequestMethod.GET)
    private String getDictionaries(HttpServletRequest request){
        List<DictionariesZero> list  = dictionariesService.findDictionariesZero();
        List<DictionariesZero> listTree = BuildTreeUtil.buildTreeZero(list,0);
        return  JSON.toJSONString(listTree);
    }


    /**
     * 获取字典表1
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getDictionariesOne",method = RequestMethod.GET)
    private String getDictionariesOne(HttpServletRequest request){
        List<DictionariesOne> list  = dictionariesServiceImp.findDictionariesOne();
        List<DictionariesOne> listTree = BuildTreeUtil.buildTreeOne(list,0);
        return  JSON.toJSONString(listTree);
    }


    /**
     * 获取字典表2
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getDictionariesTwo",method = RequestMethod.GET)
    private String getDictionariesTwo(HttpServletRequest request){
        List<DictionariesTwo> list  = dictionariesServiceImp.findDictionariesTwo();
        List<DictionariesTwo> listTree = BuildTreeUtil.buildTreeTwo(list,0);
        return  JSON.toJSONString(listTree);
    }

    /**
     * 按状态获取字典表
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getDictionariesType",method = RequestMethod.GET)
    private String getDictionariesType(HttpServletRequest request){
        String type = request.getParameter("type");
        List<Dictionaries> list  = dictionariesService.findDictionariesType(type);
        List<Dictionaries> listTree = BuildTreeUtil.buildTree(list,0);
        return  JSON.toJSONString(listTree);
    }

    /**
     * 保存字典信息
     * @param dictionaries
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/saveDictionaries",method = RequestMethod.POST)
    private String saveDictionaries(Dictionaries dictionaries, HttpServletRequest request) {
        RegEntity entity = new RegEntity();
        Integer code = -1;
        if (dictionaries.getMenuId() != null){
            Dictionaries d = dictionariesService.findById(dictionaries.getMenuId());
            d.setTitle(dictionaries.getTitle());
            if (dictionariesService.save(d).getMenuId() != null){
                code = 1;
            }
        }else{
            dictionaries.setIsShow("0");
            if (dictionaries.getParentId() == null){
                //父节点如果为空则表示新增父节点
                dictionaries.setParentId("0");
            }
            if (dictionariesService.save(dictionaries).getMenuId() != null){
                code = 1;
            }
        }
        entity.setInfoCode(code);
        entity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(entity);
    }


    /**
     * 保存字典信息1
     * @param dictionariesOne
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/saveDictionariesOne",method = RequestMethod.POST)
    private String saveDictionariesOne(DictionariesOne dictionariesOne, HttpServletRequest request) {
        RegEntity entity = new RegEntity();
        Integer code = -1;
        if (dictionariesOne.getMenuId() != null){
            DictionariesOne d = dictionariesServiceImp.findByIdOne(dictionariesOne.getMenuId());
            d.setTitle(dictionariesOne.getTitle());
            if (dictionariesServiceImp.saveOne(d).getMenuId() != null){
                code = 1;
            }
        }else{
            dictionariesOne.setIsShow("0");
            if (dictionariesOne.getParentId() == null){
                //父节点如果为空则表示新增父节点
                dictionariesOne.setParentId("0");
            }
            if (dictionariesServiceImp.saveOne(dictionariesOne).getMenuId() != null){
                code = 1;
            }
        }
        entity.setInfoCode(code);
        entity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(entity);
    }

    @ResponseBody
    @RequestMapping(value = "/saveDictionariesTwo",method = RequestMethod.POST)
    private String saveDictionariesOne(DictionariesTwo dictionariesTwo, HttpServletRequest request) {
        RegEntity entity = new RegEntity();
        Integer code = -1;
        if (dictionariesTwo.getMenuId() != null){
            DictionariesTwo d = dictionariesServiceImp.findByIdTwo(dictionariesTwo.getMenuId());
            d.setTitle(dictionariesTwo.getTitle());
            if (dictionariesServiceImp.saveTwo(d).getMenuId() != null){
                code = 1;
            }
        }else{
            dictionariesTwo.setIsShow("0");
            if (dictionariesTwo.getParentId() == null){
                //父节点如果为空则表示新增父节点
                dictionariesTwo.setParentId("0");
            }
            if (dictionariesServiceImp.saveTwo(dictionariesTwo).getMenuId() != null){
                code = 1;
            }
        }
        entity.setInfoCode(code);
        entity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(entity);
    }


    /**
     * 标识删除字典信息
     * @param dictionaries
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteDictionaries",method = RequestMethod.POST)
    private String deleteDictionaries(Dictionaries dictionaries, HttpServletRequest request) {
        RegEntity entity = new RegEntity();
        Integer code = -1;
       if (dictionaries.getMenuId() != null && dictionaries.getParentId() != null){
           if (dictionariesService.deleteDictionaries(dictionaries.getMenuId(),dictionaries.getParentId())>0){
               code = 1;
           }
       }
        entity.setInfoCode(code);
        entity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(entity);
    }

    @ResponseBody
    @RequestMapping(value = "/deleteDictionariesOne",method = RequestMethod.POST)
    private String deleteDictionariesOne(DictionariesOne dictionariesOne, HttpServletRequest request) {
        RegEntity entity = new RegEntity();
        Integer code = -1;
        if (dictionariesOne.getMenuId() != null && dictionariesOne.getParentId() != null){
            if (dictionariesServiceImp.deleteDictionariesOne(dictionariesOne.getMenuId(),dictionariesOne.getParentId())>0){
                code = 1;
            }
        }
        entity.setInfoCode(code);
        entity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(entity);
    }


    @ResponseBody
    @RequestMapping(value = "/deleteDictionariesTwo",method = RequestMethod.POST)
    private String deleteDictionariesTwo(DictionariesTwo dictionariesTwo, HttpServletRequest request) {
        RegEntity entity = new RegEntity();
        Integer code = -1;
        if (dictionariesTwo.getMenuId() != null && dictionariesTwo.getParentId() != null){
            if (dictionariesServiceImp.deleteDictionariesTwo(dictionariesTwo.getMenuId(),dictionariesTwo.getParentId())>0){
                code = 1;
            }
        }
        entity.setInfoCode(code);
        entity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(entity);
    }

    /**
     * 获取用户信息下拉
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getLevelUser",method = RequestMethod.GET)
    private String getLevelUser(HttpServletRequest request){
        Integer level = userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getLevel();
        List<Dictionaries> list  = dictionariesService.findLevelUser(level);
        return  JSON.toJSONString(list);
    }


    /**
     * 新增粉丝
     * @param houseFans
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/insertFans",method = RequestMethod.POST)
    private String insertFans(HouseFans houseFans, HttpServletRequest request) {
        RegEntity entity = new RegEntity();
        houseFans.setInfoTime(new Date().toString());
        Integer code = -1;
        if (houseFansService.save(houseFans).getId() != null){
            code = 1;
        }
        entity.setInfoCode(code);
        entity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(entity);
    }

    /**
     * 统计楼盘粉丝量
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/countFans",method = RequestMethod.GET)
    private String countFans(HttpServletRequest request){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String thisTime = sdf.format(new Date());
        return  JSON.toJSONString(houseFansService.findFans(thisTime));
    }

    /**
     * 浏览量
     * @param houseFans
     * @param request
     */
    @ResponseBody
    @RequestMapping(value = "/insertBrowseVolume",method = RequestMethod.POST)
    private void insertBrowseVolume(HouseFans houseFans, HttpServletRequest request) {
         houseFansServiceImp.addNum();
    }

    /**
     * 浏览量，咨询量
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/countBrowseVolume",method = RequestMethod.GET)
    private String countBrowseVolume(HttpServletRequest request){
        return  JSON.toJSONString(houseFansService.countBrowseVolume());
    }

    /**
     * 首页楼盘销售状态
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/countHouseNum",method = RequestMethod.GET)
    private String countHouseNum(HttpServletRequest request){
        return  JSON.toJSONString(houseFansService.countHouseNum());
    }

    @ResponseBody
    @RequestMapping(value = "/queryCustom",method = RequestMethod.GET)
    private String queryCustom(CustomReEntity customReEntity,HttpServletRequest request){
        Page<CustomerRegistration> list = customerRegistrationService.findPagedByWhereClause(customReEntity);
        return JSON.toJSONString(list);
    }

    /**
     * 获取销控图信息
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/houseMarketingControl",method = RequestMethod.GET)
    private String houseMarketingControl(UserTaskEntity userTaskEntity,HttpServletRequest request){
        return  JSON.toJSONString(houseDetailService.houseMarketingControl(userTaskEntity));
    }

    /**
     * 房源销控信息
     * @param userTaskEntity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/houseMarketingControl1",method = RequestMethod.GET)
    private String houseMarketingControl1(UserTaskEntity userTaskEntity,HttpServletRequest request){
        return  JSON.toJSONString(houseDetailService.houseMarketingControl1(userTaskEntity));
    }

    /**
     * 房源销控物业下拉
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getPropertyTye",method = RequestMethod.GET)
    private String getPropertyTye(){
        return  JSON.toJSONString(houseDetailService.getPropertyTye());
    }

    /**
     * 期数下拉
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getStage",method = RequestMethod.GET)
    private String getStage(){
        return  JSON.toJSONString(houseDetailService.getStage());
    }

    /**
     * 幢号下拉
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getBlockCode",method = RequestMethod.GET)
    private String getBlockCode(){
        return  JSON.toJSONString(houseDetailService.getBlockCode());
    }

    /**
     * 楼层下拉
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getFloorE",method = RequestMethod.GET)
    private String getFloorE(String blockCode){
        return  JSON.toJSONString(houseDetailService.getFloorE(blockCode));
    }


    @ResponseBody
    @RequestMapping(value = "/getTest")
    private String getTest(HttpServletRequest request) {
        List bb = new ArrayList();
        String type = "A,B";
        String a[] = type.split(",");
        for (String b : a){
            bb.add(b);
        }
        List houseMapParameter = houseDetailService.getTest(bb);
        return JSON.toJSONString(houseMapParameter);
    }

    /**
     * 获取用户注册时间
     * @param uid
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getInfoTime",method = RequestMethod.GET)
    private String getInfoTime(String uid,HttpServletRequest request){
        return  JSON.toJSONString(userService.findRegTime(uid));
    }

    /**
     * 根据等级查询人员信息列表
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getRoleUser",method = RequestMethod.GET)
    private String getRoleList(HttpServletRequest request){
        String level = request.getParameter("level");
        return  JSON.toJSONString(userService.getRoleUser(level));
    }

    /**
     * 根据人员查看相关权限
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getUserByJurisdiction",method = RequestMethod.GET)
    private String getUserByJurisdiction(HttpServletRequest request){
        String userIds = request.getParameter("userIds");
        return  JSON.toJSONString(userService.getUserByJurisdiction(userIds));
    }

    /**
     * 权限信息列表
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getJurisdictionList",method = RequestMethod.GET)
    private String getJurisdictionList(HttpServletRequest request){
        return  JSON.toJSONString(userService.getJurisdictionList());
    }



    /**
     * 人员分配权限列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/distributionJurisdictionList",method = RequestMethod.GET)
    private String distributionJurisdictionList(){
        return JSON.toJSONString(userService.distributionJurisdictionList());
    }

    /**
     * 验证是否拥有此权限
     * @param userId
     * @param jurisdictionId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getIsJurisdiction",method = RequestMethod.GET)
    private String getIsJurisdiction(String userId,String jurisdictionId){
        return JSON.toJSONString(userService.distributionJurisdictionList());
    }

    //分配权限
    @ResponseBody
    @RequestMapping(value = "/allocation",method = RequestMethod.POST)
    private String allocation(String userId,String jurisdictionId) {
        Integer code = -1;
        if (houseFansServiceImp.allocation(userId,jurisdictionId) > 0){
            code = 1;
        }
        RegEntity regEntity = new RegEntity();
        regEntity.setInfoCode(code);
        regEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(regEntity);
    }

    //分配权限及新增用户
    @ResponseBody
    @RequestMapping(value = "/allocationAndInsertUser",method = RequestMethod.POST)
    private String allocationAndInsertUser(String userName,String phone,String jurisdictionId,String level) {
        Integer code = -1;
        if (houseFansServiceImp.allocationAndInsertUser(userName,phone,jurisdictionId,level) == 2){
            code = -6001;
        }else{
            code = 1;
        }
        RegEntity regEntity = new RegEntity();
        regEntity.setInfoCode(code);
        regEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(regEntity);
    }

    /**
     * 获取客户公池列表
     */
    @ResponseBody
    @RequestMapping(value = "/queryPublicCustomerList",method = RequestMethod.GET)
    private String queryPublicCustomerList(HttpServletRequest request){
        String name = request.getParameter("name");
        return JSON.toJSONString(customerRegistrationService.queryPublicCustomerList(name));
    }


    /**
     * 人为分配
     * @param customerRegistration
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/artificialDistribution",method = RequestMethod.POST)
    private String artificialDistribution(CustomerRegistration customerRegistration){
        Integer code = -1;
        RegEntity regEntity = new RegEntity();
        if (customerRegistrationService.artificialDistribution(customerRegistration) > 0){
            code = 1;
        }
        regEntity.setInfoCode(code);
        regEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(regEntity);
    }


    /**
     * 随机分配
     * @param customReEntity
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/randomAllocation",method = RequestMethod.POST)
    private String randomAllocation(CustomReEntity customReEntity){
        Integer code = -1;
        String name = null;
        RegEntity regEntity = new RegEntity();
        Integer customerNum = customerRegistrationService.queryPublicCustomerList(name).size(); //获取用户数量
        if (customerNum == 0){
            code = -4398;
        }
        Integer userIdNum = userService.queryUserNum().size();//获取销售数量
        List<CustomerRegistration> cl = customerRegistrationService.queryPublicCustomerList(name);
        List<User> ul = userService.queryUserNum();
        if (customerNum == userIdNum){ //执行一对一操作
            for (int a = 0;a < ul.size(); a++){
                customReEntity.setCustomId(cl.get(a).getId());
                customReEntity.setReceptionId(ul.get(a).getId().toString());
                customReEntity.setReceptionName(ul.get(a).getName());
                if (customerRegistrationService.randomAllocation(customReEntity) > 0){
                    code = 1;
                }
            }
        }else{ //执行用户id随机
            for (int b = 0;b < cl.size(); b++){
                customReEntity.setCustomId(cl.get(b).getId());
                Integer bb= (int)(Math.random()*ul.size()); //随机产生用户id
                customReEntity.setReceptionId(ul.get(bb).getId().toString());
                customReEntity.setReceptionName(ul.get(bb).getName());
                if (customerRegistrationService.randomAllocation(customReEntity) > 0){
                    code = 1;
                }
            }
        }
        regEntity.setInfoCode(code);
        regEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(regEntity);
    }

    @ResponseBody
    @RequestMapping(value = "/queryXk",method = RequestMethod.GET)
    private String queryXk(HttpServletRequest request){
        return JSON.toJSONString(houseDetailService.getXk());
    }


    @ResponseBody
    @RequestMapping(value = "/downloadExcel",method = RequestMethod.GET)
    public void downloadExcel(HttpServletResponse response,HttpServletRequest request) {
        try {
            //获取文件的路径
            String excelPath = request.getSession().getServletContext().getRealPath("/mb/" + "备案价格表.xls");
            String fileName = "备案价格表.xls".toString(); // 文件的默认保存名
            // 读到流中
            InputStream inStream = new FileInputStream(excelPath);//文件的存放路径
            // 设置输出的格式
            response.reset();
            response.setContentType("bin");
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("备案价格表.xls", "UTF-8"));
            // 循环取出流中的数据
            byte[] b = new byte[200];
            int len;
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //导入客户基本信息
    @ResponseBody
    @RequestMapping(value = "/importCustomerList",method = RequestMethod.POST)
    private String importCustomerList(@RequestParam("file") MultipartFile uploadFile,HttpServletRequest request) {
        if (uploadFile == null) {
            //判断文件大小
            return "上传文件为空文档";
        }
        Integer code = -1;
        BaseEntity baseEntity =new BaseEntity();
        customerService.importCustomerList(uploadFile,request);
        baseEntity.setInfoCode(code);
        baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return  JSON.toJSONString(baseEntity);
    }


    @ResponseBody
    @RequestMapping(value = "/updateMarketingControl",method = RequestMethod.POST)
    private String updateMarketingControl(HouseDetail houseDetail) {
        Integer code = -1;
        houseDetail.setArtificial(houseDetail.getArtificial());
        if (houseDetailService.updateHouseInfo(houseDetail)){
            code = 1;
        }
        RegEntity regEntity = new RegEntity();
        regEntity.setInfoCode(code);
        regEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(regEntity);
    }

    /**
     * 查询置业顾问信息
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getReceptionList",method = RequestMethod.GET)
    private String getReceptionList(HttpServletRequest request){
        return  JSON.toJSONString(userService.getReceptionList());
    }

    /**
     * 查询用户本身信息
     * @param response
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/myDetail",method = RequestMethod.GET)
    public String myDetail(HttpServletResponse response, HttpServletRequest request){
        Integer uid = userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId();
        return JSON.toJSONString(userService.findById(uid));
    }


    //参加活动
    @ResponseBody
    @RequestMapping(value = "/takePartIn",method = RequestMethod.POST)
    public String articleList(HttpServletRequest request) {
        int artId = Integer.parseInt(request.getParameter("artId"));
        String userName = request.getParameter("userName");
        String phone = request.getParameter("phone");
        String level = request.getParameter("level");
        String type = request.getParameter("type");
        String userId = request.getParameter("userId");
        String notLogge = request.getParameter("notLogge");

        Date d = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String x = df.format(d);
        //获取活动信息
        List<Article> articleList = articleService.findByEndTimeAndRegion(artId);
        for (int i =0;i< articleList.size();i++){
            String endTime = (articleList.get(i).getEndTime()).toString();
            String region = articleList.get(i).getRegion();
            // 判断活动时间是否过期
            if(x.compareTo(endTime) > 0){
                BaseEntity baseEntity = new BaseEntity();
                baseEntity.setInfoCode(-4396);
                baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(-4396));
                return JSON.toJSONString(baseEntity);
            }
            //超级奖励判断是否符合权限设计   分销聚会则不判断
            if (!type.equals("2")){   //2 分销聚会
                String[] regions = region.split(",");
                for (String qx : regions) {
                    if (!qx.equals(level)){
                        BaseEntity baseEntity = new BaseEntity();
                        baseEntity.setInfoCode(101);
                        baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(101));
                        return JSON.toJSONString(baseEntity);
                    }
                }
                //是否满足条件1
                String one = "0"; //判定条件1
                String two = "0"; //判断条件2
                if (one.equals("1") || two.equals("1")){
                    BaseEntity baseEntity = new BaseEntity();
                    baseEntity.setInfoCode(-1032);
                    baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(-1032));
                    return JSON.toJSONString(baseEntity);
                }
            }
        }
        Integer uid = null;
        if (!notLogge.equals("y")){
             uid = userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId();
        }else{
        //用手机号查询用户信息
            if (uid == null){   //此用户不在系统中或未登录
                User yw = userService.findByTelePhone(phone);
                if (yw != null){   //存在系统中但未登录
                    uid = userService.findByTelePhone(phone).getId();
                }else{    //不存在系统中则自行录入系统
                    User user = new User();
                    user.setTelephone(phone);
                    user.setName(userName);
                    user.setIntegral(0); //没有积分
                    user.setPwd(bCryptPasswordEncoder.encode("123456")); //默认密码
                    user.setLevel(1);
                    user.setStatus(1);
                    user.setRegTime(new Date());
                    uid = userService.insert(user).getId();
                }
            }
        }
        int code = activeService.takePartIn(uid,artId);
        BaseEntity entity = new BaseEntity();
        entity.setInfoCode(code);
        entity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(entity);
    }



    /**
     * 导出客户信息
     * @param customReEntity
     * @param response
     * @param request
     */
    @RequestMapping(value = "/exportCustomerData", method = {RequestMethod.GET,RequestMethod.POST})
    public void exportCustomerData(CustomReEntity customReEntity, HttpServletResponse response, HttpServletRequest request) {
        //xls格式最大存储行数
        Integer max = 65535;
        customReEntity.setPageNumber(1);
        customReEntity.setPageSize(max);
        List<CustomerRegistration> list = new ArrayList<>();
        List<String> header = new ArrayList<>();
        List<String> field = new ArrayList<>();
        String tmpName = null;
        list = customerRegistrationService.findPagedByWhereClause(customReEntity).getContent();
        /*if (customReEntity.getTmp() != null){
        String[] values = customReEntity.getTmp().split(",");
        for (String id : values) {
            String name = dictionariesZeroRepository.findType(id);
            String kay = name.substring(0,name.indexOf(","));
            if (kay.equals("zycs")){
                tmpName = "置业次数";
            }else if(kay.equals("khly")){
                tmpName = "客户来源";
            }else if (kay.equals("khnjd")){
                tmpName = "客户年纪段";
            }else if(kay.equals("yxwylx")){
                tmpName = "意向物业类型";
            }else if(kay.equals("qy")){
                tmpName = "区域";
            }else if (kay.equals("dfcs")){
                tmpName = "到访次数";
            }else if (kay.equals("hztj")){
                tmpName = "获知途径";
            }else if (kay.equals("mjxq")){
                tmpName = "面积需求";
            }else if (kay.equals("zjxq")){
                tmpName = "总价需求";
            }else if (kay.equals("fkfs")){
                tmpName = "付款方式";
            }else if (kay.equals("hxxq")){
                tmpName = "户型需求";
            }else if (kay.equals("klys")){
                tmpName = "考虑因素";
            }else if (kay.equals("jgjsd")){
                tmpName = "价格接受度";
            }else if (kay.equals("yxhx")){
                tmpName = "意向户型";
            }else if (kay.equals("jjyy")){
                tmpName = "拒绝原因";
            }else if(kay.equals("khzy")){
                tmpName = "客户职业";
            }else if(kay.equals("jtjg")){
                tmpName = "家庭结构";
            }else if(kay.equals("khzt")){
                tmpName = "客户状态";
            }else if(kay.equals("tfyy")){
                tmpName = "退房原因";
            }else if(kay.equals("sfkgybf")){
                tmpName = "是否看过样板房";
            }
        }
        }*/
        //excel表格头
        header.add("姓名");
        header.add("电话");
        header.add("年龄");
        header.add("地址");
        header.add("客户评级");
        header.add("置业次数");
        header.add("意向物业");
        header.add("购房目的");

        header.add("到访次数");
        header.add("总价需求");
        header.add("面积需求");
        header.add("获知途径");
        header.add("付款方式");
        header.add("户型需求");
        header.add("意向户型");
        header.add("考虑因素");

        header.add("客户职业");
        header.add("家庭结构");
        header.add("价格接受度");
        header.add("是否看过样板房");
        header.add("拒绝原因");
        header.add("退房原因");


        header.add("客户状态");


        //对应实体字段
        field.add("name");
        field.add("phone");
        field.add("age");
        field.add("address");
        field.add("level");
        field.add("homeOwnership");
        field.add("intentionPropertyType");
        field.add("purchasePurpose");
        field.add("comeNum");
        field.add("totalNeed");
        field.add("areaNeed");
        field.add("accessKnowledge");
        field.add("paymentType");
        field.add("houseTypeNeed");
        field.add("intentionalHouseholdType");
        field.add("considerType");

        field.add("customerOccupation");
        field.add("familyStructure");
        field.add("priceAcceptance");
        field.add("modelHouses");
        field.add("refuseReason");
        field.add("checkOutReason");

        field.add("customerType");


        /*if(tmpName != null){
            if (tmpName.equals("置业次数")){
                field.add("homeOwnership");
            }else if (tmpName.equals("客户来源")){
                field.add("customerSource");
            }else if (tmpName.equals("拒绝原因")){
                field.add("refuseReason");
            }else if (tmpName.equals("客户年纪段")){
                field.add("age");
            }else if (tmpName.equals("意向物业类型")){
                field.add("intentionPropertyType");
            }else if (tmpName.equals("区域")){
                field.add("areaName");
            }else if (tmpName.equals("到访次数")){
                field.add("comeNum");
            }else if (tmpName.equals("获知途径")){
                field.add("accessKnowledge");
            }else if (tmpName.equals("面积需求")){
                field.add("areaNeed");
            }else if (tmpName.equals("总价需求")){
                field.add("totalNeed");
            }else if (tmpName.equals("付款方式")){
                field.add("paymentType");
            }else if (tmpName.equals("户型需求")){
                field.add("houseTypeNeed");
            }else if (tmpName.equals("考虑因素")){
                field.add("considerType");
            }else if (tmpName.equals("价格接受度")){
                field.add("priceAcceptance");
            }else if (tmpName.equals("客户职业")){
                field.add("customerOccupation");
            }else if (tmpName.equals("家庭结构")){
                field.add("familyStructure");
            }else if (tmpName.equals("客户状态")){
                field.add("customerType");
            }else if (tmpName.equals("意向户型")){
                field.add("intentionalHouseholdType");
            }else if (tmpName.equals("退房原因")){
                field.add("checkOutReason");
            }else if (tmpName.equals("是否看过样板房")){
                field.add("modelHouses");
            }
        }*/


        HSSFWorkbook xssfSheets = ExcelUtil.exportCustomerExcel(list, header.toArray(new String[0]), field.toArray(new String[0]),"客户表信息");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        OutputStream outputStream = null;
        StringBuilder sb = new StringBuilder();
        try {
            xssfSheets.write(os);
            byte[] bytes = os.toByteArray();
            response.reset();
            response.setContentType("application/ms-excel;charset=UTF-8");
            sb.append("客户表信息");
            sb.append(".xls");
            String filename = URLEncoder.encode(sb.toString(), "utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 新增E类客户
     * @param customerRegistration
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/insertCustomerEType",method = RequestMethod.POST)
    private String insertCustomerEType(CustomerRegistration customerRegistration){
        Integer code = -1;
        RegEntity regEntity = new RegEntity();
        customerRegistration.setCustomerSource("外拓");
        if (customerRegistrationService.insertCustomerEType(customerRegistration) > 0){
            code = 1;
        }
        regEntity.setInfoCode(code);
        regEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(regEntity);
    }
}
